// 歌曲列表
let musiclist = []
// 当前播放歌曲索引
let playingIndex = 0
let nowPlayingMusic = {}
const backgroundAudioManager = wx.getBackgroundAudioManager()
const app = getApp()
Page({
  data: {
    picUrl: '',
    isPlaying: false,
    isLyricShow: false,
    lyric: '',
    isSame: false,
  },

  onLoad: function(options) {
    playingIndex = options.musicIndex
    const playingId = parseInt(options.musicId)
    musiclist = wx.getStorageSync('musiclist')
    this._getMusicDetail(playingId)
  },
  _getMusicDetail(musicId) {
    console.log(musicId, app.getMusicPlayingId())
    if (musicId == app.getMusicPlayingId()) {
      this.setData({
        isSame: true,
        isPlaying: true,
      })
    } else {
      this.setData({
        isSame: false,
        isPlaying: false,
      })
      backgroundAudioManager.stop()
    }

    nowPlayingMusic = musiclist[playingIndex]
    this.setData({
      picUrl: nowPlayingMusic.al.picUrl,
    })
    wx.setNavigationBarTitle({
      title: nowPlayingMusic.name,
    })
    app.setMusicPlayingId(musicId)
    app.loading('歌曲加载中')
    // 请求获取歌曲信息
    wx.cloud.callFunction({
      name: 'music',
      data: {
        musicId,
        $url: 'musicUrl',
      }
    }).then((res) => {
      console.log(this.data.isSame)
      let music = res.result.data[0]
      if (!this.data.isSame) {
        backgroundAudioManager.title = nowPlayingMusic.name
        backgroundAudioManager.epname = nowPlayingMusic.al.name
        backgroundAudioManager.singer = nowPlayingMusic.ar[0].name
        backgroundAudioManager.coverImgUrl = nowPlayingMusic.al.picUrl
        if (!music.url) {
          wx.hideLoading()
          wx.showModal({
            title: '提示',
            content: '当前歌曲无版权，播放失败',
            showCancel: false,
            confirmColor: '#d43c43',
            success(res) {
              if (res.confirm) {
                wx.navigateBack()
              }
            },
          })
          return false
        }
        let songTime = backgroundAudioManager.duration
        if (typeof songTime != 'undefined') {
          backgroundAudioManager.src = music.url
          this.savePlayHistory()
          this.setData({
            isPlaying: true
          })
          wx.hideLoading()
        } else {
          setTimeout(() => {
            backgroundAudioManager.src = music.url
            this.savePlayHistory()
            this.setData({
              isPlaying: true
            })
            wx.hideLoading()
          }, 1000)
        }
      } else {
        wx.hideLoading()
      }
    })

    // 请求歌曲歌词信息
    wx.cloud.callFunction({
      name: 'music',
      data: {
        musicId,
        $url: 'lyric'
      }
    }).then((res) => {
      console.log('歌词信息', res)
      let lyricData = res.result
      let lyric = '暂无歌词'
      if (lyricData.lrc) {
        lyric = lyricData.lrc.lyric
      }
      this.setData({
        lyric
      })
    })
  },
  // 播放/暂停按钮操作
  togglePlaying() {
    if (this.data.isPlaying) {
      backgroundAudioManager.pause()
    } else {
      backgroundAudioManager.play()
    }
    this.setData({
      isPlaying: !this.data.isPlaying
    })
  },
  // 上一首
  onPrev() {
    playingIndex--
    if (playingIndex < 0) {
      playingIndex = musiclist.length - 1
    }
    this._getMusicDetail(musiclist[playingIndex].id)
    app.setMusicPlayingId(musiclist[playingIndex].id)
  },
  // 下一首
  onNext() {
    playingIndex++
    if (playingIndex === musiclist.length) {
      playingIndex = 0
    }
    this._getMusicDetail(musiclist[playingIndex].id)
    app.setMusicPlayingId(musiclist[playingIndex].id)
  },
  onPlay() {
    this.setData({
      isPlaying: true
    })
  },
  onPause() {
    this.setData({
      isPlaying: false
    })
  },
  // 控制歌词的显示
  _controlLyricShow() {
    this.setData({
      isLyricShow: !this.data.isLyricShow
    })
  },
  // 接收歌词组件传来的当前歌曲播放时间
  lyricTimeUpdate(e) {
    let lyricTime = e.detail.currentTime
    this.selectComponent('.lyric-components').updateTime(lyricTime)
  },
  // 保存最近播放记录
  savePlayHistory() {
    let openid = app.globalData.openid
    let playing = musiclist[playingIndex]
    let history = wx.getStorageSync(openid)
    let played = false
    for (let i = 0; i < history.length; i++) {
      if (history[i].id == playing.id) {
        played = true
        break
      }
    }
    if (!played) {
      history.unshift(playing)
      wx.setStorage({
        key: openid,
        data: history,
      })
    }
  },
})